package com.ly.mpayment.persist.service.downproductlog;

import java.io.Serializable;
import java.util.Map;

import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.persist.entity.DownShopProduct;
import com.ly.mpayment.persist.entity.User;
import org.springframework.stereotype.Service;

import com.ly.mpayment.persist.entity.DownProductLog;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.AbstractService;

@Service
public class DownProLogServiceImpl extends AbstractService<DownProductLog, Serializable> implements IDownProLogService {

	@Override
	public boolean addDownprolog(DownProductLog log) {
		if(log != null){
			this.saveOrUpdate(log);
			return true;
		}
		return false;
	}

	@Override
	public boolean updateDownprolog(DownProductLog log) {
		if(log != null){
			this.saveOrUpdate(log);
			return true;
		}
		return false;
	}

	@Override
	public DownProductLog findById(String id) {
		return this.findUnique("select d from DownProductLog d where d.downloguuid = ?", id);
	}

	@Override
	public Page<DownProductLog> findPageDownprolog(Map<String, Object> parameters, int start, int pageSize) {
		String hql = " select d from DownProductLog d left join fetch d.downShopProduct p left join fetch p.user pu left join fetch d.userLog " +
				" where 1 = 1 #[and d.downShopProduct.user.useruuid = :useruuid]#";

		if(parameters.containsKey(":starttime")){
			hql += "and DATE_FORMAT(d.createtime,'%Y-%m-%d') >= '"+parameters.get(":starttime") +"' ";
			parameters.remove(":starttime");
		}

		if(parameters.containsKey(":endtime")){
			hql += "and DATE_FORMAT(d.createtime,'%Y-%m-%d') <= '"+parameters.get(":endtime") +"' ";
			parameters.remove(":endtime");
		}

		hql += "  order by d.createtime desc  ";

		return this.findPageByNamed(hql, parameters, start, pageSize);
	}

	@Override
	public boolean addLog(DownShopProduct product, User user, String downName, String upName) {
		DownProductLog log = null;
		log = new DownProductLog();
		log.setOperationtarget(Config.product[1]);
		log.setDownShopProduct(product);
		log.setRemark("匹配产品:"+downName+"->"+upName);
		if(user != null){
			log.setUserLog(user);
		}
		addDownprolog(log);
		return true;
	}

	@Override
	public void deleteLog(DownShopProduct product) {
		this.getSession().createSQLQuery("delete from downproductlog where downprouuid = '"+product.getDownprouuid()+"'").executeUpdate();
	}
}
